//
//  OrderEditViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/10/29.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

enum OrderEditType {
    case recommender
    case manager
    case feastingDate
}

class OrderEditViewController: UIViewController {
    
    var editType: OrderEditType?
    
    var order: UserOrderDetail?
    
    var orderVM: OrderViewModel?
    
    var completion: (() -> Void)?
    
    let disposeBag = DisposeBag()
    
    let editField: UITextField = {
        let textfield = UITextField()
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        textfield.keyboardType = .default
        return textfield
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        if let type = editType {
            switch type {
            case .feastingDate:
                setViewFeastingDate()
            case .recommender:
                setViewRecommender()
            case .manager:
                setViewManager()
            }
        }
        setBackBarItem()
        
        let rightBt = UIButton()
        rightBt.contentHorizontalAlignment = .right
        rightBt.setTitle(LanguageHelper.getString(key: "SUBMIT"), for: .normal)
        rightBt.setTitleColor(doneItemButtonColor, for: .normal)
        rightBt.addTarget(self, action: #selector(submit(_:)), for: .touchUpInside)
        rightBt.sizeToFit()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBt)
        
        initVM()
    }
    
    func setViewFeastingDate() {
        self.navigationItem.title = LanguageHelper.getString(key: "SET_FEAST_DATE")
        self.editField.placeholder = LanguageHelper.getString(key: "CHOOSE_DATE")
        self.editField.isEnabled = false
        let fdView = UIView()
        fdView.backgroundColor = UIColor.white
        fdView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        let titleLabel = UILabel()
        titleLabel.font = AppFont(size: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.text = LanguageHelper.getString(key: "FEAST_DATE")
        let maxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleWidth = TextSize.textSize(text: titleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        titleLabel.frame = UIEdgeInsetsInsetRect(fdView.bounds, UIEdgeInsetsMake(10, 10, 10, fdView.bounds.width - titleWidth - 10))
        editField.frame = UIEdgeInsetsInsetRect(fdView.bounds, UIEdgeInsetsMake(10, fdView.bounds.width - 100 - 10, 10, 10))
        let fdSaperator = UIView()
        fdSaperator.backgroundColor = lightSaperatorColor
        fdSaperator.frame = UIEdgeInsetsInsetRect(fdView.bounds, UIEdgeInsetsMake(fdView.bounds.height - 0.5, 0, 0, 0))
        fdView.addSubview(editField)
        fdView.addSubview(titleLabel)
        fdView.addSubview(fdSaperator)
        self.view.addSubview(fdView)
    }
    
    func setViewRecommender() {
        self.navigationItem.title = LanguageHelper.getString(key: "SET_RECOMMENDER")
        self.editField.placeholder = LanguageHelper.getString(key: "WRITE_RECOMMENDER")
        let recoView = UIView()
        recoView.backgroundColor = UIColor.white
        recoView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        let titleLabel = UILabel()
        titleLabel.font = AppFont(size: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.text = LanguageHelper.getString(key: "RECOMMENDER")
        let maxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleWidth = TextSize.textSize(text: titleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        titleLabel.frame = UIEdgeInsetsInsetRect(recoView.bounds, UIEdgeInsetsMake(10, 10, 10, recoView.bounds.width - titleWidth - 10))
        editField.frame = UIEdgeInsetsInsetRect(recoView.bounds, UIEdgeInsetsMake(10, recoView.bounds.width - 100 - 10, 10, 10))
        let recoSaperator = UIView()
        recoSaperator.backgroundColor = lightSaperatorColor
        recoSaperator.frame = UIEdgeInsetsInsetRect(recoView.bounds, UIEdgeInsetsMake(recoView.bounds.height - 0.5, 0, 0, 0))
        recoView.addSubview(editField)
        recoView.addSubview(titleLabel)
        recoView.addSubview(recoSaperator)
        self.view.addSubview(recoView)
    }
    
    func setViewManager() {
        self.navigationItem.title = LanguageHelper.getString(key: "SET_MANAGER")
        self.editField.placeholder = LanguageHelper.getString(key: "WRITE_MANAGER")
        let managerView = UIView()
        managerView.backgroundColor = UIColor.white
        managerView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        let titleLabel = UILabel()
        titleLabel.font = AppFont(size: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.text = LanguageHelper.getString(key: "MANAGER")
        let maxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleWidth = TextSize.textSize(text: titleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        titleLabel.frame = UIEdgeInsetsInsetRect(managerView.bounds, UIEdgeInsetsMake(10, 10, 10, managerView.bounds.width - titleWidth - 10))
        editField.frame = UIEdgeInsetsInsetRect(managerView.bounds, UIEdgeInsetsMake(10, managerView.bounds.width - 100 - 10, 10, 10))
        let managerSaperator = UIView()
        managerSaperator.backgroundColor = lightSaperatorColor
        managerSaperator.frame = UIEdgeInsetsInsetRect(managerView.bounds, UIEdgeInsetsMake(managerView.bounds.height - 0.5, 0, 0, 0))
        managerView.addSubview(editField)
        managerView.addSubview(titleLabel)
        managerView.addSubview(managerSaperator)
        self.view.addSubview(managerView)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self.view)
            if editField.frame.contains(point) {
                if editType == .feastingDate {
                    self.pickADate()
                }
            } else {
                editField.resignFirstResponder()
            }
            
        }
    }

    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                orderVM = OrderViewModel(token: token)
            }
        }
    }
    
    func submit(_ sender: UIBarButtonItem) {
        if let type = editType {
            switch type {
            case .manager:
                updateManager()
            case .feastingDate:
                updateFeastingDate()
            case .recommender:
                updateRecommender()
            }
        }
    }
    
    func updateRecommender() {
        
    }
    
    func updateManager() {
        if let vm = orderVM {
            if let manager = editField.text {
                vm.updateManager(id: (order?.id)!, username: manager).subscribe(onNext: { [unowned self] response in
                    print(response)
                    if let status = response.status {
                        if status != 200 {
                            self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                        }
                    } else {
                        if let success = response.success {
                            if success {
                                if let function = self.completion {
                                    function()
                                }
                                self.navigationController?.popViewController(animated: true)
                            } else {
                                if let data = response.data {
                                    self.showPromptView(message: data, confirmText: LanguageHelper.getString(key: "OK"))
                                } else {
                                    self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                                }
                            }
                        }
                    }
                    }, onError: { error in
                        self.showPromptView(message: LanguageHelper.getString(key: "OPERATION_FAIL"), confirmText: LanguageHelper.getString(key: "OK"))
                })
                .addDisposableTo(disposeBag)
            }
        }
    }
    
    func updateFeastingDate() {        
        if let vm = orderVM {
            if let date = editField.text {
                vm.updateFeastingDate(id: (order?.id)!, date: date).subscribe(onNext: { [unowned self] response in
                    if response == "true" {
                        if let function = self.completion {
                            function()
                        }
                        self.navigationController?.popViewController(animated: true)
                    } else {
                        self.showPromptView(message: response, confirmText: LanguageHelper.getString(key: "OK"))
                    }
                })
                .addDisposableTo(disposeBag)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func pickADate() {
        let view = CalendarViewController()
        view.selectType = .single
        view.afterPickDates = { [unowned self] beginDate, endDate in
            self.editField.text = beginDate
        }
        self.navigationController?.pushViewController(view, animated: true)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
